package com.service.impl;

import com.bean.*;
import com.dao.FlowerDao;
import com.dao.OrderDao;
import com.dao.OrderItemDao;
import com.dao.impl.FlowerDaoImpl;
import com.dao.impl.OrderDaoImpl;
import com.dao.impl.OrderItemDaoImpl;
import com.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao=new OrderDaoImpl();
    private OrderItemDao orderItemDao=new OrderItemDaoImpl();
    private FlowerDao flowerDao=new FlowerDaoImpl();

    @Override
    public String createOrder(Cart cart, String userid) {
        //订单号唯一
        String orderid=System.currentTimeMillis()+""+userid;
        //创建订单对象
        Order order=new Order(orderid,new Date(),cart.getTotalPrice(),0,userid);
        //保存订单
        orderDao.saveOrder(order);
        //遍历购物车,将商品项转化为订单项
        for(Map.Entry<Integer, CartItem>entry:cart.getItems().entrySet()){
            //获取每一个购物车中的商品项
            CartItem cartItem=entry.getValue();
            //转换为每一个订单项
            OrderItem orderItem=new OrderItem(cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),cartItem.getId(),cartItem.getEnterpriseid(),orderid);
            //保存订单项
            orderItemDao.saveOrderItem(orderItem);

            Flower flower=flowerDao.queryFlowerByFlowerid(cartItem.getId());
            flower.setSales(flower.getSales()+cartItem.getCount());
            flower.setStock(flower.getStock()-cartItem.getCount());

            flowerDao.updateFlowerByFlower(flower.getSales(),flower.getStock(),flower.getFlowerid());
        }
        cart.clear();
        return orderid;
    }
    @Override
    public List<Order> showMyOrders(String userid) {
        return orderDao.queryByUserid(userid);
    }

    @Override
    public List<Order> showMyOrdersa(String userid, int status) {
        return orderDao.showMyOrdersa(userid,status);
    }
}
